/**
 * @file router.js
 */
"use strict";

const env = process.env.mode || "dev";
const plural = require("plural");
const req = require("request-promise");
const path = require("path");
const extend = require("util")._extend;
const config = require(path.join("..", "..", "config", env, "server"))[env];

/**
 * Simple router, handles basic route.
 *
 * @class Router
 */
class Router {
  /**
   * @constructor
   * @param {string} url - url to fetch to, need to be singular
   * @example
   *  ```
   *  let subject = new Router("pet");
   *  console.log(subject.param.item); // return "pet"
   *  console.log(subject.param.list); // return "pets"
   *  ```
   */
  constructor(url) {
    let root = config.api.uri;
    this.param = {
      item: root + "/" + url,
      list: root + "/" + plural(url)
    };
    this.uri = extend(config.api);
  }

  /**
   * Fetch a list of the given url.
   *
   * @method requestAll
   * @return {Promise} list
   */
  requestAll() {
    let payload = extend(this.uri);
    payload.uri = this.param.list;
    return req(payload)
      .then(response => response);
  }

  /**
   * Fetch an item of the given url.
   *
   * @method requestOne
   * @param {string|number} property
   * @return {Promise} item
   * @example
   *  ```
   *  let subject = new Router("pet");
   *  subject.requestOne(1)
   *    .then(item => console.log(item)); // return item
   *  ```
   */
  requestOne(property) {
    if (!property) {
      let message = {
        status: "error",
        message: "Router: requestOne property wrong"
      };
      return Promise.reject(message);
    }
    let payload = extend(this.uri);
    payload.uri = this.param.item + "/" + property;
    return req(payload)
      .then(response => response);
  }
}

module.exports = Router;
